﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace LdCms.Web.Controllers.API.Sms.V1
{
    using LdCms.IBLL.Member;
    using LdCms.IBLL.Sms;
    using LdCms.Web.Services;
    using LdCms.Common.Extension;
    using LdCms.EF.DbModels;
    using LdCms.Common.Security;
    using LdCms.Common.Utility;
    using LdCms.Plugins.Sms.Tencent;
    using LdCms.Common.Json;
    using LdCms.Common.Time;

    [ApiVersion("1.0")]
    [ControllerName("sms/tencent/sms")]
    public class SmsTencentSmsController : BaseApiController
    {
        private readonly IBaseApiManager BaseApiManager;
        private readonly ITencentPlatformService TencentPlatformService;
        private readonly ITencentSendRecordService TencentSendRecordService;
        public SmsTencentSmsController(IBaseApiManager BaseApiManager, ITencentPlatformService TencentPlatformService, ITencentSendRecordService TencentSendRecordService) : base(BaseApiManager)
        {
            this.BaseApiManager = BaseApiManager;
            this.TencentPlatformService = TencentPlatformService;
            this.TencentSendRecordService = TencentSendRecordService;
        }
        private Ld_Sms_TencentPlatform TencentPlatform
        {
            get
            {
                var entity = TencentPlatformService.GetTencentPlatformByDefault(InterfaceAccount.SystemID, InterfaceAccount.CompanyID);
                if (entity == null)
                    throw new Exception("get params fail！");
                return entity;
            }
        }
        private TencentSmsHelper TencentSmsHelper
        {
            get
            {
                string appid = TencentPlatform.AppID;
                string appkey = TencentPlatform.AppKey;
                return new TencentSmsHelper(appid, appkey);
            }
        }

        [HttpPost]
        [ActionName("send")]
        public IActionResult Send(string uuid, [FromBody]JObject fromValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(uuid, fromValue);
                bool IsParams = IsSendParams(fromValue);
                string mobile = GetJObjectValue(fromValue, "mobile");
                string code = GeneralCodeHelper.GetRandomInt(6);
                if (!Utility.IsMobilePhone(mobile))
                {
                    return Error(logId, "手机号码格式不正确！");
                }
                string[] sParams = new string[] { code };
                string sendId = GetSendId();
                string ext = new
                {
                    system_id = TencentPlatform.SystemID,
                    company_id = TencentPlatform.CompanyID,
                    platform_id = TencentPlatform.PlatformID,
                    send_id = sendId
                }.ToJson();
                var sendResult = SendSms(TencentPlatform, mobile, ext, sParams);
                SaveSendRecord(TencentPlatform, mobile, ext, sParams, sendId, sendResult);
                if (sendResult.result != 0)
                    return Error(logId, sendResult.errmsg);
                else
                    return Success(logId, "ok", new
                    {
                        pid = TencentPlatform.PlatformID,
                        sid = sendId,
                        code
                    });
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }

        #region 私有化方法
        private string GetSendId()
        {
            try
            {
                var primarykey = PrimaryKeyHelper.PrimaryKeyType.SmsTencentSendRecord;
                var primaryKeyLen = PrimaryKeyHelper.PrimaryKeyLen.V2;
                return PrimaryKeyHelper.MakePrimaryKey(primarykey, primaryKeyLen);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private string ToContent(string content, string[] sParams)
        {
            try
            {
                string result = content;
                for (var i = 0; i < sParams.Length; i++)
                {
                    result = result.Replace("{1}", sParams[i]);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private SendSmsResult SendSms(Ld_Sms_TencentPlatform entity, string mobile, string ext, string[] sParams)
        {
            try
            {
                string appid = entity.AppID;
                string appkey = entity.AppKey;
                int tplId = entity.TplID.ToInt();
                string sign = entity.Sign;
                return TencentSmsHelper.SendSmsPro(new SendSms()
                {
                    ext = ext,
                    tpl_id = tplId,
                    tel = new SendSmsTel() { nationcode = "86", mobile = mobile },
                    @params = sParams,
                    sign = sign,
                    time = TimeHelper.GetUnixTimestampTen()
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private void SaveSendRecord(Ld_Sms_TencentPlatform entity, string mobile, string ext, string[] sParams,string sendId, SendSmsResult sendSmsResult)
        {
            try
            {
                string appid = entity.AppID;
                string appkey = entity.AppKey;
                int tplId = entity.TplID.ToInt();
                string sign = entity.Sign;
                TencentSendRecordService.SaveTencentSendRecord(new Ld_Sms_TencentSendRecord()
                {
                    SystemID = entity.SystemID,
                    CompanyID = entity.CompanyID,
                    PlatformID = entity.PlatformID,
                    SendID = sendId,
                    Code = sParams[0].ToString(),
                    NationCode = "86",
                    Mobile = mobile,
                    Sign = sign,
                    Ext = ext,
                    //Extend="",
                    TplID = tplId,
                    Params = sParams.ToJson(),
                    Content = ToContent(entity.Content, sParams),
                    Time = TimeHelper.GetUnixTimestampTen(),
                    Fee = sendSmsResult.fee,
                    SId = sendSmsResult.sid,
                    ErrMsg = sendSmsResult.errmsg,
                    IsResult = sendSmsResult.result == 0 ? true : false,
                    CreateDate = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool IsSendParams(JObject fromValue)
        {
            try
            {
                if (fromValue == null)
                    throw new Exception("params not empty！");
                if (fromValue.Property("mobile") == null)
                    throw new Exception("mobile not empty！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}